/**
 * Copyright (c) 2005-2009 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: SpringContextUtils.java 422 2009-09-05 14:43:11Z calvinxiu $
 */
package jude.java.money.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;

public class ContextHolder {

	private static ApplicationContext applicationContext;
	private static ContextLoader contextLoader;
	private static String contextPath;
	
	/**
	 * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
	 */
	public static void setApplicationContext(ApplicationContext context) {
		ContextHolder.applicationContext = context;
	}
	
	public static void setContextLoader(ContextLoader contextLoader) {
		ContextHolder.contextLoader = contextLoader;
	}
	
	public static ContextLoader getContextLoader() {
		return contextLoader;
	}
	
	public static void setContextPath(String contextPath) {
		ContextHolder.contextPath = contextPath;
	}
	
	public static String getContextPath() {
		return contextPath;
	}

	/**
	 * 取得存储在静态变量中的ApplicationContext.
	 */
	public static ApplicationContext getApplicationContext() {
		if (applicationContext == null)
			throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextUtil");
		return applicationContext;
	}

	/**
	 * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		return (T) applicationContext.getBean(name);
	}
	
}
